﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Goodway.Dao.Utility;
using System.Xml.Linq;

namespace ExcelImportComponent.Valider.Implement
{
    public class ValidRep : IVaild
    {
        #region IVaild 成员

        public List<ExcelImportValidMessage> DoValid(string validColumnName, List<Goodway.Dao.Utility.GoodwayEntity> entities, XElement validSetting, string schemaname)
        {
            string message = "不能重复";
            //param[0] =DataSourceKey param[1]=TableName
            if (string.IsNullOrEmpty(validSetting.Attribute("DataSourceKey").Value)) throw new Exception("重复验证时 请输入DataSourceKey");
            if (string.IsNullOrEmpty(validSetting.Attribute("TableName").Value)) throw new Exception("重复验证时 请输入TableName");

            string dataSourceKey = validSetting.Attribute("DataSourceKey").Value;
            string tableName = validSetting.Attribute("TableName").Value;
            string columnName = validSetting.Attribute("ColumnName").Value;

            IGoodwayEntityProvider provider = GoodwayEntityProviderFactory.GetEntityProvider();
            provider.ConStr = dataSourceKey;
            provider.TableName = tableName;

            List<GoodwayEntity> list = provider.GetAll();
            List<ExcelImportValidMessage> returnValue = new List<ExcelImportValidMessage>();
            for (int i = 0; i < entities.Count; i++)
            {
                GoodwayEntity entity = entities[i];
                GoodwayEntity enumEntity = list.FirstOrDefault(p => p[columnName]==entity[validColumnName]);
                List<GoodwayEntity> myList = entities.FindAll(p => p[validColumnName]==entity[validColumnName]);
                if (enumEntity != null || myList.Count >= 2)
                {
                    ExcelImportValidMessage objMessage = new ExcelImportValidMessage(i.ToString(), validColumnName);
                    objMessage.Value = entity[validColumnName];
                    objMessage.ErrorMessage.Add(message);
                    returnValue.Add(objMessage);
                }
            }
            return returnValue;
        }

        #endregion
    }
}
